430. Flatten a Multilevel Doubly Linked List - LeetCode Solution


LinkedList DFS

Python Code:

"""
# Definition for a Node.
class Node:
    def __init__(self, val, prev, next, child):
        self.val = val
        self.prev = prev
        self.next = next
        self.child = child
"""

class Solution:
    def trav(self,head1):
        root = head1
        if not root:
            return None
        while root:
            a = None
            if root.child:
                a = self.trav(root.child) 
            if a:
               
                a.prev = head1
                
                temp = root.next
               
                root.next = a
                while root.next:
                    root = root.next
                
                root.next = temp

            root = root.next
        return head1
                
                
    def flatten(self, head: 'Node') -> 'Node':
        if not head:
            return None
        
        
        root = self.trav(head)
        temp = root
        temp.prev = None
        temp.child= None
        last = temp
        temp = temp.next
        while temp:
            temp.child = None
            temp.prev = last
            last = temp
            temp = temp.next
            
        
        return root


Comments

Submit
0 Comments
More Questions

78A - Haiku
1287A - Angry Students
1428A - Box is Pull
234B - Reading
581B - Luxurious Houses
1481C - Fence Painting
935A - Fafa and his Company
22A - Second Order Statistics
1720B - Interesting Sum
1720A - Burenka Plays with Fractions
3A - Shortest path of the king
1720C - Corners
574A - Bear and Elections
352B - Jeff and Periods
1244A - Pens and Pencils
1670A - Prof Slim
1189A - Keanu Reeves
678A - Johny Likes Numbers
1699C - The Third Problem
1697D - Guess The String
754B - Ilya and tic-tac-toe game
760A - Petr and a calendar
1573A - Countdown
166A - Rank List
1631B - Fun with Even Subarrays
727A - Transformation from A to B
822B - Crossword solving
1623A - Robot Cleaner
884B - Japanese Crosswords Strike Back
862B - Mahmoud and Ehab and the bipartiteness